/*
 * @Author: LBH 1336709799@qq.com
 * @Date: 2023-05-20 11:03:20
 * @LastEditors: LBH 1336709799@qq.com
 * @LastEditTime: 2024-11-30 16:04:28
 * @FilePath: \heima-hr\src\permission.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import router, { asyncRoutes } from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'

/**
 *前置守卫
 *
*/

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  if (store.getters.token) {
    // 存在token
    if (to.path === '/login') {
      // 跳转到主页
      next('/') // 中转到主页
      // next（地址）并没有执行后置守卫
      nprogress.done()
    } else {
      // 获取用户资料的前提: 1.有token 2.去的不是登陆页
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        // 遍历动态路由,一旦匹配成功,添加到路由表中
        const filterRoutes = asyncRoutes.filter(item => {
          // roles.menus 用户路由访问权限集合
          return roles.menus.includes(item.name)
        })
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        // 提交mutation 更新routes
        store.commit('user/setRoutes', filterRoutes)
        next(to.path)
      } else {
        next()
      }
      // 放行
    }
  } else {
    // 没有token
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login') // 中转到登录页
      nprogress.done()
    }
  }
})

/** *
 * 后置守卫
 * **/
router.afterEach(() => {
  nprogress.done()
})
